package servlets.user;

import hibernate.method.UserMethods;
import hibernate.model.User;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import external.EmailUtility;
import external.TokenGenerator;

/**
 * Servlet implementation class passwordReminder
 */
@WebServlet("/passwordReminder")
public class passwordReminder extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String host;
	private String port;
	private String user;
	private String pass;
    /**
     * @see HttpServlet#HttpServlet()
     */
	
	public void init() {
		// reads SMTP server setting from web.xml file
		ServletContext context = getServletContext();
		host = context.getInitParameter("host");
		port = context.getInitParameter("port");
		user = context.getInitParameter("user");
		pass = context.getInitParameter("pass");
	}
	
    public passwordReminder() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String toAddress = (String) request.getParameter("email");
		String username= (String) request.getParameter("username");
		
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		UserMethods user_m = new UserMethods();
		User u = user_m.is_user(sessionFactory, session, username).get(0);
		
		if(u.getEmail().equals(toAddress)){
			try{
				String token = TokenGenerator.generateToken();
			
			user_m.insertToken(sessionFactory, session, token, "passwordReminder", user_m.is_user(sessionFactory, session, username).get(0).getUser_id(), toAddress);
			String tresc = EmailUtility.sendPasswordReminderMail(TokenGenerator.linkWithToken(token, "passwordReminder", user_m.is_user(sessionFactory, session, username).get(0).getUser_id()), user_m.is_user(sessionFactory, session, username).get(0).getUsername());
			
			EmailUtility.sendEmail(host, port, user, pass, toAddress, "[HexGames Social] Resetowanie hasła", tresc);
			
			
			session.getTransaction().commit();
				out.println("<script type=\"text/javascript\">alert(\"Procedura resetowania hasla powiodla sie. Na podany adres email wyslalismy wiadomosc z dalszymi wskazowkami\"); window.location.href = \"social/index.jsp?page=main\";</script>");
			}
			catch (Exception e){ 
				out.println("<script type=\"text/javascript\">alert(\"Procedura resetowania hasla zakonczyla sie niepowodzeniem. Za utrudnienia przepraszamy\"); window.location.href = \"social/index.jsp?page=main\";</script>");
			}
			session.close();
			
			
			
		}
		
	}

}
